package org.automated.realestatemanager.parsers;

import java.util.Set;

import org.apache.log4j.Logger;
import org.automated.realestatemanager.dataanaliser.Analyzer;
import org.automated.realestatemanager.db.entity.Advertisement;
import org.automated.realestatemanager.db.entity.Agency;
import org.automated.realestatemanager.db.entity.Phone;
import org.automated.realestatemanager.db.entity.Publisher;
import org.automated.realestatemanager.db.services.ServiceFactory;

public class CentrDomAgenciesParcer {

	private static final Logger log = Logger.getLogger(AgencyParser.class);

	Agency agency = null;
	int counter = 0;
	Advertisement advertisement = null;
	Publisher publisher = null;
	String source = "estate-in-kharkov.com";

	public void executeParcing(final String name, final String agencyName,
			Set<Phone> phones, final String status, final String source) {

		counter++;

		ServiceFactory.getInstance();
		this.agency = ServiceFactory.getAgencyService().getAgencyByName(
				agencyName);
		if (this.agency == null) {
			this.agency = ServiceFactory.getAgencyService().create(
					new Agency(agencyName));
		}

		if (phones == null)
			log.error("No phones available");
		publisher = Analyzer.getPhonesOwner(phones);
		if (publisher == null) {
			publisher = new Publisher();
		}

		publisher.setAgency(this.agency);

		if (publisher.getName() != null && publisher.getName().isEmpty()) {
			publisher.setName(name);
		}

		if (publisher.getStatus() != null && publisher.getStatus().isEmpty()) {
			publisher.setStatus(status);
		}

		if (publisher.getSource() != null && publisher.getSource().isEmpty()) {
			publisher.setSource(source);
		}

		phones = ServiceFactory.getInstance().getPhoneService()
				.persistPhones(phones);

		if (phones.size() == 0)
			return;

		boolean publisherExist = false;
		if (publisher == null) {
			log.debug("Publisher not found");
			publisher = new Publisher();
			// publisher.setName(ParserUtils.parseName(text));

		} else {
			log.debug("Publisher found");
			publisherExist = true;
		}

		publisher.getPhones().addAll(phones);
		publisher.getAdvertisements().add(advertisement);
		if (publisherExist) {
			ServiceFactory.getInstance().getPublisherService().merge(publisher);
		} else {
			ServiceFactory.getInstance().getPublisherService()
					.create(publisher);
		}

		log.debug("Publisher saved");
		phones.clear();
	}

	public String getSource() {
		return source;
	}

	public void setSource(final String source) {
		this.source = source;
	}

}
